from flask import Flask, render_template, request, make_response
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
import json

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///m1314.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False # 打开事件系统，照抄
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, nullable=False, primary_key=True)
    username = db.Column(db.String(30), nullable=False)
    password = db.Column(db.String(30), nullable=False)
    permission = db.Column(db.Integer, nullable=False, default=2)
    dateCreated = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)

    def __repr__(self):
        return '<User %r>' % self.id

#class Email(db.Model):
#    pass

def judgeCookie(userData):
    users = User.query.all()
    for user in users:
        if user.username == userData['username'] and user.password == userData['password']:
            return str(user.permission)
    return False


@app.route('/')
@app.route('/login', methods=['POST', 'GET'])
def login_route():
    if request.method == 'POST':
        # get information from client
        userData = request.form
        print(userData['username'])
        print(userData['password'])

        u_permission = judgeCookie(userData)
        if u_permission:
            resp = make_response('true') 
            resp.set_cookie('information', json.dumps({'username': userData['username'], 'password':
                userData['password'], 'permission':u_permission}), max_age=3600)
            return resp
        else:
            return 'false'
    else:
        # get user cookie
        try:
            userCookie = json.loads(request.cookies.get('information'))
            print(userCookie)
            if judgeCookie(userCookie):
                return render_template('home.html')
        except:
            return render_template('login.html')

@app.route('/register', methods=['POST', 'GET'])
def sign_route():
    if request.method == 'POST':
        # get information from client
        userData = request.form
        #print(userData['username'])
        #print(userData['password'])
        #print(userData['permission'])
        #print("===========")
        # get all user information
        users = User.query.all()
        #print(users)
        #print(users[0].username)
        #print(users[0].password)
        for user in users:
            # judge 1 or 0 had been sign(0-->actor, 1-->actress)
            if (userData['permission'] == str(user.permission) and userData['permission'] != '2'):
                return json.dumps({"is": False, "message": 'just you'})
            # judge username had been sign
            elif (userData['username'] == user.username):
                return json.dumps({"is": False, "message": 'account already exists'})
        user = User(id=len(users), username=userData['username'], password=userData['password'], permission=userData['permission'])
        try:
            db.session.add(user)
            db.session.commit()
            return json.dumps({"is": True, "message": 'registration success'})
        except Exception as e:
            print(e)
            return json.dumps({"is": False, "message": 'There was an issue'})
    else:
        return render_template('register.html')

if __name__ == '__main__':
    db.create_all()
    app.run(host='0.0.0.0', debug=True)
